<template>
    <div>
        <div class="commonStyle nyContent" style="padding-bottom: 20px; min-height: 730px">
            <div class="commonTit">凭证管理列表</div>
            <div class="table-operator">
                <a-button type="primary" @click="$refs.createCert.showModal()" >生成凭证</a-button>
                <div class="importFile">
                    <a-button type="primary" style="float: right;" class="btnGreen" >
                        导入证书
                    </a-button>
                    <input ref="sendFile" type="file" name="fileName"  @change="importCert($event)" accept=".zip" required />
                </div>
            </div>
            <a-table :columns="columns" :dataSource="loadData" :rowKey="record => record.id"
                     :pagination="false">
                <span slot="index" slot-scope="text, record, index">
                    {{ (page.pageNo - 1) * page.pageSize + index + 1 }}
                </span>
                <span slot="notBefore" slot-scope="text, record, index">
                    {{text}} 至 {{record.notAfter}}
                </span>
                <template v-for="col in ['subject', 'certFingerprint']" :slot="col" slot-scope="text, record, index">
                    <div :key="col">
                        <ellipsis :length="20" tooltip :fullString="text"></ellipsis>
                    </div>
                </template>
                <span slot="operation" slot-scope="text" class="table-operation">
                    <a @click="exportCert(text.id)">下载</a>
                  <!--  <a @click="$refs.detail.showModal(text,'client')">详情</a>-->
                    <a @click="delCert(text)" class="adel" v-if="delClientCertFlag">删除</a>
                </span>
            </a-table>
            <Page :totalCount="page.total" :currentPage="page.pageNo" ref="page"
                  :pageSize="page.pageSize"
                  @changePage="changePage" @changePageSize="changePageSize" />
        </div>
        <create-cert ref="createCert" @init="init" />
        <detail ref="detail"/>
    </div>
</template>

<script>
    import verify from 'libs/verify'
    import { mapState } from 'vuex'
    import createCert from './createCert.vue'
    import detail from './detail.vue'
    import Util from '@/libs/util'
    import Page from 'module/pagination'
    import ellipsis from 'module/ellipsis'
    export default {
        name: 'clientCertList',
        components: {
            Page,
            ellipsis,
            detail,
            createCert
        },
        data () {
            return {
                form: this.$form.createForm (this),
                verify,
                spinning: false,
                spinText: '请稍后...',
                timer: null,
                page: {
                    name: undefined,
                    deviceModelNumber: '',
                    pageNo: 1,
                    pageSize: 10,
                    totalCount: 0
                },
                columns: [
                    {title: '序号', key: 'index', width: '80px', align: 'center', scopedSlots: {customRender: 'index'}},
                    {title: '客户端名称', dataIndex: 'certFingerprint', key: 'certFingerprint', scopedSlots: {customRender: 'certFingerprint'}},
                    {title: '凭证名称', dataIndex: 'subject', key: 'subject', scopedSlots: {customRender: 'subject'}},
                    {title: '颁发者', dataIndex: 'algorithm', key: 'algorithm'},
                    {title: '生效日期', dataIndex: 'notBefore', key: 'notBefore', scopedSlots: {customRender: 'notBefore'}},
                    {title: '失效日期', dataIndex: 'notAfter', key: 'notAfter', scopedSlots: {customRender: 'notAfter'}},
                    {title: '操作', key: 'operation', width: '140px', scopedSlots: {customRender: 'operation'}}
                ],
                loadData: [],
                title:false,
                delClientCertFlag:false
            }
        },
        computed: {
            ...mapState ({
                formStyle: state => state.common.formStyle,
            })
        },
        created () {
            //this.init()
        },
        methods: {
            emitEmpty ( partant, name ) {
                this[ partant ][ name ] = ''
                this.init ()
            },
            reStore () {
                this.page.deviceModelNumber = ''
                this.page.manufacturerName = undefined
                this.page.pageNo = 1
                this.init ()
            },
            /*
             * 过滤输入框输入的特殊字符
             * */
            formatEnterContent ( value ) {
                let a = Util.clearSpecialChart (value)
                this.page.deviceModelNumber = a
            },
            init () {
                let _this = this
                _this.$get ('api/hsm/certificates/client/findClientCerts',this.page).then (res => {
                    _this.page.total = res.total
                    _this.loadData = res.rows
                })
            },
            /**
             * Function    : clearListTimer
             * Description : 关闭定时器
             * Input       : none
             * Return      : none
             */
            clearListTimer () {
                let _this = this
                if (_this.timer !== null) {
                    clearInterval (_this.timer)
                    _this.timer = null
                }
            },
            /**
             * Function    : changePage
             * Description : 切换页码
             * Input       : val
             * Return      : none
             */
            changePage ( val ) {
                this.page.pageNo = val
                this.init ()
            },

            /**
             * Function    : changePageSize
             * Description : 切换每页条数
             * Input       : vm
             * Return      : none
             */
            changePageSize ( vm ) {
                this.page.pageSize = vm
                this.page.pageNo = 1
                this.init ()
            },

            /**
             * Function    : handleSubmit
             * Description : 查询按钮
             * Input       : none
             * Return      : none
             */
            handleSubmit () {
                this.page.pageNo = 1
                this.init ()
            },
            delCert(text){
                this.$confirm ({
                    title: `确定要删除 ${text.fileName} 证书吗?`,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        let _this = this
                        _this.$post ('/v1/sm2-ca-certs', {fileName:text.fileName}).then (res => {
                            if (res.code === 0) {
                                _this.$message.success(`删除 ${text.subject} 证书成功！`)
                                if (_this.loadData.length === 1 && _this.page.currentPage > 1) {
                                    _this.page.currentPage = _this.page.currentPage - 1
                                }
                                _this.init()
                            } else {
                                _this.$message.error(res.message)
                                _this.spinning = false
                                _this.spinText = '加载'
                            }
                        })
                    }
                })
            },
            /**
             * Function    : importCert
             * Description : 导入证书
             * Input       : none
             * Return      : none
             */
            importCert(e) {
                let _this = this
                let file = e.target.files[0]
                let indexDot = file.name.lastIndexOf('.')
                if (file.name.substr(indexDot + 1, 3) !== 'zip') {
                    _this.$message.warning('请选择.zip')
                    return
                }
                let formData = new FormData()
                formData.append('fileName',file.name)
                formData.append('fileBody', file)
                _this.spinning = true
                _this.$uploadPost('/v1/sm2-ca-certs', formData).then(res => {
                    if (res.code === 0) {
                        _this.$message.success(res.message)
                        _this.init()
                    } else {
                        _this.$message.error(res.message)
                    }
                    if (this.$refs.sendFile !== undefined) {
                        this.$refs.sendFile.value = ''
                    }
                    _this.spinning = false
                })
            },
            /**
             * Function    : exportCert
             * Description : 导出证书
             * Input       : none
             * Return      : none
             */
            exportCert(id) {
                let _this = this;
                _this.$confirm ({
                    title: `是否导出证书? `,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        _this.spinning = true
                        _this.$get ('/v1/sm2-ca-certs',{fileName:fileName}).then (res => {
                            if (res.code === 0) {
                                _this.downLoadJson(res.data)
                            } else {
                                _this.$message.error (res.message)
                            }
                            _this.spinning = false
                        }).catch((e) => {
                            _this.spinning = false
                        })
                    }
                })
            },
            downLoadJson(data){
                let blob = ''
                blob =new Blob([this.decodeToArrayBuffer (data.fileBody)])
                let url =URL.createObjectURL(blob)
                let element = document.createElement('a')
                element.style.display = 'none'
                element.href= url
                element.download = data.fileName
                element.click()
            },
            decodeToArrayBuffer(str){
                let bstr = atob(str)
                let length = bstr.length
                let unit8Array = new Uint8Array(length)
                for(let i=0;i<length;i++){
                    unit8Array[i] = bstr.charCodeAt(i)
                }
                return unit8Array.buffer
            },
        },
        destroyed () {
            this.clearListTimer ()
        }
    }
</script>
<style lang="less">
    .centerBtn {
        button {
            width: 200px;
            text-align: center;
            margin: 15px 20px 20px 0px
        }
    }
</style>
